package com.xinchengxd.chat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinchengxd.chat.dto.MsgDTO;
import com.xinchengxd.commons.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.EncodeException;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 姚新成
 * @Date: 2021/11/17:11:22
 * @Description:
 */

@Slf4j
@Component
@ServerEndpoint(value = "/chat/{user}", encoders = MyEncode.class, decoders = MyDecoder.class)
public class ChatService {

    private static Map<String, Session> m = new ConcurrentHashMap<>();

    @OnOpen
    public void opOpen(@PathParam("user") String user, Session session) throws IOException, EncodeException {
        log.debug("连接已建立！用户：{}", user);

        if (m.containsKey(user)) {
            ResponseResult<String> responseResult = new ResponseResult<>(101,"登录异常","用户已登录");
            session.getBasicRemote().sendObject(responseResult);
            session.close();
        } else {
            m.put(user, session);
            System.out.println(m.keySet());
            System.out.println(session);
        }

        /*设置统一响应*/
        Set<String> users = m.keySet();
        ResponseResult<Set<String>> responseResult = new ResponseResult<>();
        responseResult.setCode(200);
        responseResult.setMsg("用户列表");
        responseResult.setData(users);

        /*发送给全部连接对象*/
        Set<Session> openSessions = session.getOpenSessions();
        openSessions.forEach(s ->{
            try {
                s.getBasicRemote().sendObject(responseResult);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        });
    }

    @OnMessage
    public void onMessage(ResponseResult<String> msg, Session session) {
        Set<Session> openSessions = session.getOpenSessions();

        MsgDTO msgDTO = new MsgDTO();
        msgDTO.setMsg(msg.getData());
        msgDTO.setTime(new Date());
        for (Map.Entry<String,Session> entry: m.entrySet()
             ) {
            if(entry.getValue()==session){
                msgDTO.setUserName(entry.getKey());
            }
        }
        ResponseResult<MsgDTO> res = new ResponseResult<>(204,"服务器发出的消息",msgDTO);

        System.out.println("msgDTO:"+ msgDTO.toString());


        /*根据传入的数据中用户名，从map中选择指定的对象发送消息*/



        openSessions.forEach(s -> {
            try {
                s.getBasicRemote().sendObject(res);
            } catch (IOException | EncodeException e) {
                e.printStackTrace();
            }
        });
        log.debug("接受的消息为：{}", msg);
    }
}
